<template>
  <div class="chat-container">
    <div class="header">
      <div class="logo">
        <div class="logo-icon">AI</div>
        <div class="logo-text">DeepSeek Chat</div>
      </div>
      <div class="actions">
        <button @click="clearChat"><i class="fas fa-trash"></i> 清空对话</button>
        <button @click="toggleTheme"><i class="fas fa-moon"></i> 切换主题</button>
      </div>
    </div>

    <div class="chat-messages" ref="messagesContainer">
      <div v-for="(message, index) in messages" :key="index" :class="['message', message.sender]">
        <div class="avatar">
          <i :class="message.sender === 'user' ? 'fas fa-user' : 'fas fa-robot'"></i>
        </div>
        <div class="message-content">
          {{ message.text }}
        </div>
      </div>

      <div v-if="isTyping" class="message ai">
        <div class="avatar">
          <i class="fas fa-robot"></i>
        </div>
        <div class="message-content">
          <div class="typing-indicator">
            <div class="typing-dot"></div>
            <div class="typing-dot"></div>
            <div class="typing-dot"></div>
          </div>
        </div>
      </div>
    </div>

    <div class="input-area">
      <textarea
          class="message-input"
          v-model="userInput"
          placeholder="输入消息..."
          @keydown.enter.prevent="sendMessage"
          rows="1"
          ref="textInput"
          @input="adjustTextareaHeight"
      ></textarea>
      <button class="send-button" @click="sendMessage" :disabled="isLoading">
        <i class="fas fa-paper-plane"></i>
      </button>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'ChatBot',
  data() {
    return {
      messages: [
        {sender: 'ai', text: '你好！我是你的AI助手，有什么我可以帮助你的吗？'}
      ],
      userInput: '',
      isLoading: false,
      isTyping: false,
      // sessionId: 'default_session_' + Math.random().toString(36).substr(2, 9),
      sessionId: "zuozuo",
      apiBaseUrl: process.env.VUE_APP_API_URL || 'http://localhost:8000'
    };
  },
  mounted() {
    this.scrollToBottom();
    // 加载历史记录
    this.loadChatHistory();
  },
  methods: {
    async sendMessage() {
      if (!this.userInput.trim() || this.isLoading) return;

      const message = this.userInput.trim();
      this.userInput = '';
      this.messages.push({
        sender: 'user',
        text: message
      });

      this.isLoading = true;
      this.isTyping = true;
      this.scrollToBottom();
      this.adjustTextareaHeight();

      try {
        const response = await axios.post(`${this.apiBaseUrl}/chat`, {
          message: message,
          session_id: this.sessionId,
          language: '中文'
        });

        // 移除打字指示器
        this.isTyping = false;

        // 使用打字机效果显示AI回复
        const aiResponse = response.data.response;
        this.displayTypingEffect(aiResponse);
      } catch (error) {
        console.error('Error:', error);
        this.isTyping = false;
        this.messages.push({
          sender: 'ai',
          text: '抱歉，我遇到了一个问题。请稍后再试。'
        });
        this.isLoading = false;
        this.scrollToBottom();
      }
    },

    displayTypingEffect(text) {
      this.messages.push({
        sender: 'ai',
        text: ''
      });

      const messageIndex = this.messages.length - 1;
      let currentIndex = 0;

      const typingInterval = setInterval(() => {
        if (currentIndex < text.length) {
          this.messages[messageIndex].text += text[currentIndex];
          currentIndex++;
          this.scrollToBottom();
        } else {
          clearInterval(typingInterval);
          this.isLoading = false;
        }
      }, 20); // 调整速度，数值越小越快
    },

    async loadChatHistory() {
      try {
        const response = await axios.get(`${this.apiBaseUrl}/history/${this.sessionId}`);
        if (response.data.messages && response.data.messages.length > 0) {
          // 转换API响应格式到组件格式
          this.messages = response.data.messages.map(msg => ({
            sender: msg.role === 'user' ? 'user' : 'ai',
            text: msg.content
          }));
        }
        this.scrollToBottom();
      } catch (error) {
        console.error('Error loading chat history:', error);
      }
    },

    async clearChat() {
      try {
        await axios.delete(`${this.apiBaseUrl}/history/${this.sessionId}`);
        this.messages = [
          {sender: 'ai', text: '你好！对话已重置，有什么我可以帮助你的吗？'}
        ];
      } catch (error) {
        console.error('Error clearing chat:', error);
      }
    },

    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.messagesContainer;
        if (container) {
          container.scrollTop = container.scrollHeight;
        }
      });
    },

    adjustTextareaHeight() {
      this.$nextTick(() => {
        const textInput = this.$refs.textInput;
        if (textInput) {
          textInput.style.height = 'auto';
          textInput.style.height = Math.min(textInput.scrollHeight, 150) + 'px';
        }
      });
    },

    toggleTheme() {
      document.body.classList.toggle('light-theme');
    }
  }
};
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

body {
  background: linear-gradient(135deg, #1a1c25, #0e1016);
  color: #e1e1e1;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

.chat-container {
  width: 100%;
  max-width: 900px;
  height: 90vh;
  background: rgba(25, 28, 36, 0.9);
  border-radius: 16px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.header {
  padding: 20px;
  background: rgba(20, 22, 30, 0.95);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.logo {
  display: flex;
  align-items: center;
  gap: 12px;
}

.logo-icon {
  width: 36px;
  height: 36px;
  background: linear-gradient(135deg, #6e8efb, #a777e3);
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
}

.logo-text {
  font-size: 22px;
  font-weight: 700;
  background: linear-gradient(135deg, #6e8efb, #a777e3);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.actions button {
  background: rgba(255, 255, 255, 0.1);
  border: none;
  color: #a2a2b5;
  padding: 8px 15px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  margin-left: 10px;
}

.actions button:hover {
  background: rgba(255, 255, 255, 0.15);
  color: #fff;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 25px;
}

.message {
  display: flex;
  gap: 15px;
  max-width: 85%;
}

.message.user {
  align-self: flex-end;
}

.message.ai {
  align-self: flex-start;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  font-size: 18px;
}

.user .avatar {
  background: linear-gradient(135deg, #6e8efb, #a777e3);
}

.ai .avatar {
  background: linear-gradient(135deg, #43cea2, #185a9d);
}

.message-content {
  background: rgba(255, 255, 255, 0.05);
  padding: 15px;
  border-radius: 12px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  line-height: 1.5;
  white-space: pre-wrap;
}

.user .message-content {
  background: rgba(110, 142, 251, 0.15);
  border: 1px solid rgba(110, 142, 251, 0.2);
}

.ai .message-content {
  background: rgba(33, 150, 243, 0.1);
  border: 1px solid rgba(33, 150, 243, 0.2);
}

.input-area {
  padding: 20px;
  background: rgba(20, 22, 30, 0.95);
  border-top: 1px solid rgba(255, 255, 255, 0.1);
  display: flex;
  gap: 15px;
}

.message-input {
  flex: 1;
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  padding: 15px;
  color: #e1e1e1;
  font-size: 16px;
  resize: none;
  min-height: 60px;
  max-height: 150px;
  outline: none;
  transition: border 0.3s;
}

.message-input:focus {
  border: 1px solid rgba(110, 142, 251, 0.5);
}

.send-button {
  background: linear-gradient(135deg, #6e8efb, #a777e3);
  border: none;
  color: white;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  align-self: flex-end;
  cursor: pointer;
  font-size: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: transform 0.2s;
}

.send-button:hover:not(:disabled) {
  transform: scale(1.05);
}

.send-button:active:not(:disabled) {
  transform: scale(0.95);
}

.send-button:disabled {
  background: rgba(110, 142, 251, 0.5);
  cursor: not-allowed;
}

/* 滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 8px;
}

.chat-messages::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 4px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: rgba(110, 142, 251, 0.5);
  border-radius: 4px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background: rgba(110, 142, 251, 0.7);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-container {
    height: 95vh;
    border-radius: 12px;
  }

  .message {
    max-width: 90%;
  }

  .header {
    padding: 15px;
  }

  .logo-text {
    font-size: 18px;
  }
}

.typing-indicator {
  display: flex;
  gap: 5px;
  padding: 10px 0;
}

.typing-dot {
  width: 8px;
  height: 8px;
  background: #6e8efb;
  border-radius: 50%;
  animation: typingAnimation 1.4s infinite ease-in-out;
}

.typing-dot:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-dot:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typingAnimation {
  0%, 60%, 100% {
    transform: translateY(0);
    opacity: 0.5;
  }
  30% {
    transform: translateY(-10px);
    opacity: 1;
  }
}

/* 浅色主题 */
body.light-theme {
  background: linear-gradient(135deg, #f5f7fa, #e4e7eb);
  color: #2d3748;
}

body.light-theme .chat-container {
  background: rgba(255, 255, 255, 0.9);
  border: 1px solid rgba(0, 0, 0, 0.1);
}

body.light-theme .header {
  background: rgba(248, 250, 252, 0.95);
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}

body.light-theme .actions button {
  background: rgba(0, 0, 0, 0.05);
  color: #4a5568;
}

body.light-theme .actions button:hover {
  background: rgba(0, 0, 0, 0.1);
  color: #1a202c;
}

body.light-theme .message-content {
  background: rgba(0, 0, 0, 0.03);
  border: 1px solid rgba(0, 0, 0, 0.1);
}

body.light-theme .user .message-content {
  background: rgba(110, 142, 251, 0.1);
  border: 1px solid rgba(110, 142, 251, 0.2);
}

body.light-theme .ai .message-content {
  background: rgba(33, 150, 243, 0.08);
  border: 1px solid rgba(33, 150, 243, 0.15);
}

body.light-theme .input-area {
  background: rgba(248, 250, 252, 0.95);
  border-top: 1px solid rgba(0, 0, 0, 0.1);
}

body.light-theme .message-input {
  background: rgba(0, 0, 0, 0.03);
  border: 1px solid rgba(0, 0, 0, 0.1);
  color: #2d3748;
}

body.light-theme .message-input:focus {
  border: 1px solid rgba(110, 142, 251, 0.5);
}

body.light-theme .chat-messages::-webkit-scrollbar-track {
  background: rgba(0, 0, 0, 0.03);
}

body.light-theme .chat-messages::-webkit-scrollbar-thumb {
  background: rgba(110, 142, 251, 0.4);
}

body.light-theme .chat-messages::-webkit-scrollbar-thumb:hover {
  background: rgba(110, 142, 251, 0.6);
}
</style>